import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import Cookie from 'js-cookie'
import router from '../router'
import { showFullScreenLoading, tryHideFullScreenLoading } from './serveLoading'

const service = axios.create({
  baseURL: 'http://localhost:9000',
  timeout: 15000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(function (config) {
  const random = Math.random().toString(36).substring(7)
  config.url += `?random=${random}`
  let token = Cookie.get('token')
  if (!token) {
    // console.log(config)
    return config
  } else {
    showFullScreenLoading()
    config.headers['token'] = token
    return config
  }
}, function (error) {
  tryHideFullScreenLoading()
  return Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(
  response => {
    tryHideFullScreenLoading()
    const res = response.data
    if (res.code !== 200) {
      Message({
        message: res.description || res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      // 401权限过期或无跳转到登录界面
      if (res.code === 401) {
        // to re-login
        MessageBox.alert('你的token已过期,请重新登录', '提示', {
          confirmButtonText: '回到登录页',
          callback: action => {
            Cookie.remove('token')
            localStorage.clear()
            router.push('login')
          }
        })
      }
    }
    return res
  },
  error => {
    if (error.response === undefined) {
      Message({
        message: error.message,
        type: 'error',
        duration: 5 * 1000
      })
    } else {
      if (error.response.status === 401) {
        MessageBox.alert('你的token已过期,请重新登录', '提示', {
          confirmButtonText: '回到登录页',
          callback: action => {
            Cookie.remove('token')
            localStorage.clear()
            router.push('login')
          }
        })
      }
      Message({
        message: error.response.data.message || error.response.data.description,
        type: 'error',
        duration: 5 * 1000
      })
    }
    tryHideFullScreenLoading()
    return Promise.reject(error)
  }
)

export default service
